﻿using System;
using System.Collections.Generic;
using System.Text;

using Csla;
using Csla.Data;

using System.Data;
using System.Drawing;
using System.IO;
using System.Data.SqlClient;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

using buildingLib.security;
using buildingLib.daily;

namespace buildingLib
{
    [Serializable()]
    public class Owner : BusinessBase<Owner>, security.IACL,security.ILogItem
    {
        #region ACL
        public Guid ACLID
        {
            get { return new Guid("{F23BDC44-8F25-428a-984E-2F554496865B}"); }
        }

        public string ACLName
        {
            get { return "业主信息"; }
        }

        public string ACLCategory
        {
            get { return "客服"; }
        }

        public string ACLDescription
        {
            get { return "业主个人基本信息管理"; }
        }

        public static Guid GetACLID()
        {
            return new Guid("{F23BDC44-8F25-428a-984E-2F554496865B}");
        }
       
        #endregion

        #region ILogItem
        public Guid PKey
        {
            get { return m_id; }
        }
        public int SKey
        {
            get { return 0; }
        }
        #endregion


        #region Busines Methods



        Guid m_id;
        string m_name = string.Empty;
        bool m_gender = true;
        string m_folk = string.Empty;
        string m_propertyType = string.Empty;
        string m_IDCard = string.Empty;
        DateTime m_birthDate = DateTime.Today;
        string m_company = string.Empty;
        string m_orginalAddress = string.Empty;
        string m_tel = string.Empty;
        string m_mobile = string.Empty;
        DateTime m_checkinDate = DateTime.Today;
        Guid m_doorid;
        bool m_selfpay = false;
        string m_paycompany = string.Empty;
        string m_paycompanyaddr = string.Empty;
        string m_paycompanyer = string.Empty;
        string m_paycompanytel = string.Empty;
        string m_email = string.Empty;
        //2011-03-09 
        string m_memo = string.Empty;
        bool m_companypay = false;
        double m_selfpayamount = 0;
        string m_paytype = string.Empty;
        string m_payzipcode = string.Empty;
        string m_paymemo = string.Empty;

        //集合类型

        Members m_members;
        Renters m_renters;
        Foreigners m_foreigners;
        Pets m_pets;
        buildingLib.daily.CarCers m_cars;

        public CarCers Cars
        {
            get { return m_cars; }
        }

        public Guid ID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_id;
            }
        }

        public Members RelationMembers
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_members;
            }
        }



        public Pets Pets
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_pets;
            }
        }

        public Foreigners Foreigners
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_foreigners;
            }
        }

        public Renters Renters
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_renters;
            }
        }
        public Guid DoorID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_doorid;
            }
        }

        public string Name
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_name;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_name != value)
                {
                    m_name = value;
                    PropertyHasChanged();
                }
            }
        }

        public string Memo
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_memo;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_memo != value)
                {
                    m_memo = value;
                    PropertyHasChanged();
                }
            }
        }



        public string Email
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_email;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_email != value)
                {
                    m_email = value;
                    PropertyHasChanged();
                }
            }
        }

        public string PayCompany
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_paycompany;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_paycompany != value)
                {
                    m_paycompany = value;
                    PropertyHasChanged();
                }
            }
        }

        public string PayCompanyAddr
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_paycompanyaddr;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_paycompanyaddr != value)
                {
                    m_paycompanyaddr = value;
                    PropertyHasChanged();
                }
            }
        }

        public string PayCompanyer
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_paycompanyer;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_paycompanyer != value)
                {
                    m_paycompanyer = value;
                    PropertyHasChanged();
                }
            }
        }

        public string PayType
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_paytype;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_paytype != value)
                {
                    m_paytype = value;
                    PropertyHasChanged();
                }
            }
        }

        public string PayMemo
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_paymemo;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_paymemo != value)
                {
                    m_paymemo = value;
                    PropertyHasChanged();
                }
            }
        }

        public string PayCompanyTel
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_paycompanytel;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_paycompanytel != value)
                {
                    m_paycompanytel = value;
                    PropertyHasChanged();
                }
            }
        }

        public bool SelfPay
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_selfpay;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);

                if (m_selfpay != value)
                {
                    m_selfpay = value;
                    PropertyHasChanged();
                }
            }
        }

        public bool CompanyPay
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_companypay;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);

                if (m_companypay != value)
                {
                    m_companypay = value;
                    PropertyHasChanged();
                }
            }
        }

        public bool Gender
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_gender;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);

                if (m_gender != value)
                {
                    m_gender = value;
                    PropertyHasChanged();
                }
            }
        }

        public string Folk
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_folk;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_folk != value)
                {
                    m_folk = value;
                    PropertyHasChanged();
                }
            }
        }

        public string PropertyType
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_propertyType;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_propertyType != value)
                {
                    m_propertyType = value;
                    PropertyHasChanged();
                }
            }
        }

        public string PayZipCode
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_payzipcode;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_payzipcode != value)
                {
                    m_payzipcode = value;
                    PropertyHasChanged();
                }
            }
        }

        public string IDCard
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_IDCard;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_IDCard != value)
                {
                    m_IDCard = value;
                    PropertyHasChanged();
                }
            }
        }

        public double SelfPayAmount
        {
            get { CanReadProperty(true); return m_selfpayamount; }
            set
            {
                CanWriteProperty(true);
                if (m_selfpayamount != value)
                {
                    m_selfpayamount = value;
                    PropertyHasChanged();
                }
            }
        }

        public DateTime BirthDate
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_birthDate;
            }

            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (m_birthDate != value)
                {
                    m_birthDate = value;
                    PropertyHasChanged();
                }
            }
        }

        public string Company
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_company;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_company != value)
                {
                    m_company = value;
                    PropertyHasChanged();
                }
            }
        }

        public string Address
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_orginalAddress;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_orginalAddress != value)
                {
                    m_orginalAddress = value;
                    PropertyHasChanged();
                }
            }
        }

        public string Tel
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_tel;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_tel != value)
                {
                    m_tel = value;
                    PropertyHasChanged();
                }
            }
        }

        public string Mobile
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_mobile;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_mobile != value)
                {
                    m_mobile = value;
                    PropertyHasChanged();
                }
            }
        }

        public DateTime CheckinDate
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_checkinDate;
            }

            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (m_checkinDate != value)
                {
                    m_checkinDate = value;
                    PropertyHasChanged();
                }
            }
        }

        public override bool IsDirty
        {
            get { return base.IsDirty || m_members.IsDirty || m_renters.IsDirty || m_pets.IsDirty || m_foreigners.IsDirty; }
        }

        protected override object GetIdValue()
        {
            return m_id;
        }
        #endregion

        #region Validation
        protected override void AddBusinessRules()
        {
            ValidationRules.AddRule(
              Csla.Validation.CommonRules.StringRequired, "Name");
            ValidationRules.AddRule(
              Csla.Validation.CommonRules.StringMaxLength,
              new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 50));
        }
        #endregion

        #region Authorization Rules

        protected override void AddAuthorizationRules()
        {
            //AuthorizationRules.AllowWrite(
            //  "Name", "ProjectManager");
            //AuthorizationRules.AllowWrite(
            //  "Started", "ProjectManager");
            //AuthorizationRules.AllowWrite(
            //  "Ended", "ProjectManager");
            //AuthorizationRules.AllowWrite(
            //  "Description", "ProjectManager");           
        }

        
        public bool UpLoadImg(string FileName)
        {

            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DataServer"].ToString());

            // Read Image into Byte Array from Filesystem
            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);

            byte[] photo = br.ReadBytes((int)fs.Length);
            br.Close();
            fs.Close();

            SqlCommand comupload = new SqlCommand(
            "update owner set photo = @photo where id = @id", conn);

            comupload.Parameters.Add("@photo", SqlDbType.Image, photo.Length).Value = photo;
            comupload.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = m_id;
            conn.Open();
            if (comupload.ExecuteNonQuery() <= 0)
                return false;
            conn.Close();


            return true;
        }

        /// <summary>
        /// 获取业主照片
        /// </summary>
        /// <returns></returns>
        public Image GetPhoto()
        {         
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DataServer"].ToString());
            SqlCommand getImg = new SqlCommand(
                "SELECT photo from owner where id = @id and photo is not null", conn);

            getImg.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = m_id;
            
            BinaryWriter bw;                        // Streams the BLOB to the FileStream object.
            int bufferSize = 100;                   // Size of the BLOB buffer.
            byte[] outbyte = new byte[bufferSize]; // The BLOB byte[] buffer to be filled by GetBytes.
            long retval;                            // The bytes returned from GetBytes.
            long startIndex = 0;                    // The starting position in the BLOB output.

            Stream s = new MemoryStream();
            bw = new BinaryWriter(s);
            // Open the connection and read data into the DataReader.
            conn.Open();
            SqlDataReader myReader = getImg.ExecuteReader(CommandBehavior.SequentialAccess);

            if (myReader.Read())
            {
                // Create a file to hold the output.



                // Reset the starting byte for the new BLOB.
                startIndex = 0;

                // Read the bytes into outbyte[] and retain the number of bytes returned.
                retval = myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize);

                // Continue reading and writing while there are bytes beyond the size of the buffer.
                while (retval == bufferSize)
                {
                    bw.Write(outbyte);
                    bw.Flush();

                    // Reposition the start index to the end of the last buffer and fill the buffer.
                    startIndex += bufferSize;
                    retval = myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize);
                }

                // Write the remaining buffer.
                bw.Write(outbyte, 0, (int)retval);
                bw.Flush();

            }
            s.Seek(0, SeekOrigin.Begin);
            if (s.Length == 0)
                return null;
            Image img = Image.FromStream(s);


            // Close the output file.
            bw.Close();
            s.Close();
            return img;
        }
        #endregion

        #region FactoryMethod
        public static Owner NewOwner(Guid doorid)
        {
            Owner ret = DataPortal.Create<Owner>();
            ret.m_doorid = doorid;
            return ret;
        }

        public static Owner GetOwner(Guid doorid)
        {
            return DataPortal.Fetch<Owner>(new Criteria(doorid));
        }

        public static void DeleteOwner(Guid ownerid)
        {
            DataPortal.Delete(new Criteria(ownerid));
        }


        public override Owner Save()
        {
            return base.Save();
        }
        private Owner() {this.Saved+=new EventHandler<Csla.Core.SavedEventArgs>(Owner_Saved); }

        private void Owner_Saved(object sender,Csla.Core.SavedEventArgs e)
        {
            OperateLogger.SaveLog<Owner>(this);
        }

        #endregion

        #region DataAccess
        [Serializable()]
        private class Criteria
        {
            private Guid _id;
            public Guid Id
            {
                get { return _id; }
            }

            public Criteria(Guid doorid)
            { _id = doorid; }
        }

        [RunLocal()]
        protected override void DataPortal_Create()
        {
            m_id = Guid.NewGuid();
            m_members = Members.NewMembers();
            m_renters = Renters.NewRenters();
            m_pets = Pets.NewPets();
            m_foreigners = Foreigners.NewForeigners();
            m_cars = CarCers.NewCarCers();


            
            m_members.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);            
            m_renters.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);            
            m_foreigners.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);            
            m_pets.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);            
            m_cars.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);
            ValidationRules.CheckRules();
        }

        private void DataPortal_Fetch(Criteria criteria)
        {
            Database db = SQLDatabase.GetDatabase();
            DbCommand dbcom = db.GetStoredProcCommand("usp_GGetOwnerByDoorID");
            db.AddInParameter(dbcom, "id", DbType.Guid, criteria.Id);

            using (SafeDataReader dr = new SafeDataReader(db.ExecuteReader(dbcom)))
            {
                if (dr.Read())
                {
                    m_id = dr.GetGuid("id");
                    m_name = dr.GetString("name");
                    m_gender = dr.GetBoolean("gender");
                    m_folk = dr.GetString("folk");
                    m_IDCard = dr.GetString("idcard");
                    m_birthDate = dr.GetDateTime("birthDate");
                    m_orginalAddress = dr.GetString("orginalAddress");
                    m_tel = dr.GetString("tel");
                    m_mobile = dr.GetString("mobile");
                    m_checkinDate = dr.GetDateTime("checkinDate");
                    m_selfpay = dr.GetBoolean("selfpay");
                    m_company = dr.GetString("company");
                    m_paycompany = dr.GetString("paycompany");
                    m_paycompanyaddr = dr.GetString("paycompanyaddr");
                    m_paycompanyer = dr.GetString("paycompanyer");
                    m_paycompanytel = dr.GetString("paycompanytel");
                    m_propertyType = dr.GetString("property");
                    m_email = dr.GetString("email");

                    m_memo = dr.GetString("memo");
                    m_companypay = dr.GetBoolean("companypay");
                    m_selfpayamount = dr.GetDouble("selfpayamount");
                    m_paytype = dr.GetString("paytype");
                    m_payzipcode = dr.GetString("payzipcode");
                    m_paymemo = dr.GetString("paymemo");

                }
                else
                {
                    m_id = Guid.NewGuid();
                    MarkNew();
                }

                m_doorid = criteria.Id;

                //获取集合类型

                m_members = Members.GetMembers(m_id);
                m_members.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);
                m_renters = Renters.GetRenters(m_doorid);
                m_renters.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);
                m_foreigners = Foreigners.GetForeigners(m_doorid);
                m_foreigners.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);
                m_pets = buildingLib.Pets.GetPets(m_doorid);
                m_pets.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);
                m_cars = CarCers.GetCarCers(m_doorid);
                m_cars.ListChanged += new System.ComponentModel.ListChangedEventHandler(ChildListChanged);

            }
        }

        void ChildListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
        {
            PropertyHasChanged();
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Insert()
        {
            Database db = SQLDatabase.GetDatabase();
            DbCommand dbcom = db.GetStoredProcCommand("usp_GInsertOwner");
            DoInsertUpdate(dbcom);

            m_members.Update();
            m_renters.Update();
            m_foreigners.Update();
            m_pets.Update();
            m_cars.Save();
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                Database db = SQLDatabase.GetDatabase();
                DbCommand dbcom = db.GetStoredProcCommand("usp_GUpdateOwner");
                DoInsertUpdate(dbcom);
                MarkOld();
            }
            // update child objects
            m_members.Update();
            m_renters.Update();
            m_foreigners.Update();
            m_pets.Update();
            m_cars.Save();
            
        }

        private void DoInsertUpdate(DbCommand dbcom)
        {
            Database db = SQLDatabase.GetDatabase();
            db.AddInParameter(dbcom, "id", DbType.Guid, m_id);
            db.AddInParameter(dbcom, "name", DbType.String, m_name);
            db.AddInParameter(dbcom, "gender", DbType.Boolean, m_gender);
            db.AddInParameter(dbcom, "folk", DbType.String, m_folk);
            db.AddInParameter(dbcom, "propertyType", DbType.String, m_propertyType);
            db.AddInParameter(dbcom, "idcard", DbType.String, m_IDCard);
            db.AddInParameter(dbcom, "birthDate", DbType.Date, m_birthDate.Date);
            db.AddInParameter(dbcom, "company", DbType.String, m_company);
            db.AddInParameter(dbcom, "orginalAddress", DbType.String, m_orginalAddress);
            db.AddInParameter(dbcom, "tel", DbType.String, m_tel);
            db.AddInParameter(dbcom, "mobile", DbType.String, m_mobile);
            db.AddInParameter(dbcom, "checkinDate", DbType.Date, m_checkinDate.Date);
            db.AddInParameter(dbcom, "doorID", DbType.Guid, m_doorid);
            db.AddInParameter(dbcom, "selfpay", DbType.Boolean, m_selfpay);
            db.AddInParameter(dbcom, "paycompany", DbType.String, m_paycompany);
            db.AddInParameter(dbcom, "paycompanyaddr", DbType.String, m_paycompanyaddr);
            db.AddInParameter(dbcom, "paycompanyer", DbType.String, m_paycompanyer);
            db.AddInParameter(dbcom, "paycompanytel", DbType.String, m_paycompanytel);
            db.AddInParameter(dbcom, "email", DbType.String, m_email);

            //2010-03-10 added by ln: extra information
            db.AddInParameter(dbcom, "memo", DbType.String, m_memo);
            db.AddInParameter(dbcom, "companypay", DbType.Boolean, m_companypay);
            db.AddInParameter(dbcom, "paytype", DbType.String, m_paytype);
            db.AddInParameter(dbcom, "paymemo", DbType.String, m_paymemo);
            db.AddInParameter(dbcom, "selfpayamount", DbType.Double, m_selfpayamount);
            db.AddInParameter(dbcom, "payzipcode", DbType.String, m_payzipcode);

            //execute and get updated flag param
            db.ExecuteNonQuery(dbcom);
            //_timestamp = (byte[])(db.GetParameterValue(dbcom, "LastChanged"));

            

        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(m_id));
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        private void DataPortal_Delete(Criteria criteria)
        {
            Database db = SQLDatabase.GetDatabase();
            DbCommand dbcom = db.GetStoredProcCommand("usp_GDeleteOwner");
            db.AddInParameter(dbcom, "id", DbType.Guid, criteria.Id);

            db.ExecuteNonQuery(dbcom);
        }
        #endregion

        #region Exists

        public static bool Exists(Guid doorid)
        {
            ExistsCommand result;
            result = DataPortal.Execute<ExistsCommand>
              (new ExistsCommand(doorid));
            return result.Exists;
        }

        [Serializable()]
        private class ExistsCommand : CommandBase
        {
            private Guid _id;
            private bool _exists;

            public bool Exists
            {
                get { return _exists; }
            }

            public ExistsCommand(Guid doorid)
            {
                _id = doorid;
            }

            protected override void DataPortal_Execute()
            {
                Database db = SQLDatabase.GetDatabase();
                DbCommand dbcom = db.GetStoredProcCommand("usp_GGetOwnerByDoorID");
                db.AddInParameter(dbcom, "id", DbType.Guid, _id);
                using (IDataReader dr = db.ExecuteReader(dbcom))
                {
                    _exists = dr.Read();
                }
            }
        }

        #endregion
    }
}
